import Taro from '@tarojs/taro'
import type { CallbackResult } from '@tarojs/taro/types/api/general'
import { ROUTES } from '@/config'

/**
 * 路由参数类型
 */
interface RouterOptions {
  url: string
  params?: Record<string, string | number | boolean>
  success?: Taro.navigateTo.Option['success']
  fail?: Taro.navigateTo.Option['fail']
  complete?: Taro.navigateTo.Option['complete']
}

/**
 * 构建完整路由地址
 * @param url 页面路径
 * @param params 参数对象
 */
function buildUrl(url: string, params?: Record<string, string | number | boolean>): string {
  if (!params || Object.keys(params).length === 0) {
    return url
  }

  const queryString = Object.entries(params)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
    .join('&')

  return `${url}${url.includes('?') ? '&' : '?'}${queryString}`
}

/**
 * 保留当前页面，跳转到应用内的某个页面
 */
export function navigateTo(options: RouterOptions): Promise<any> {
  const url = buildUrl(options.url, options.params)

  return Taro.navigateTo({
    url,
    success: options.success,
    fail: options.fail,
    complete: options.complete,
  })
}

/**
 * 关闭当前页面，跳转到应用内的某个页面
 */
export function redirectTo(options: RouterOptions): Promise<any> {
  const url = buildUrl(options.url, options.params)

  return Taro.redirectTo({
    url,
    success: options.success,
    fail: options.fail,
    complete: options.complete,
  })
}

/**
 * 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
 */
export function switchTab(options: RouterOptions): Promise<any> {
  const url = buildUrl(options.url, options.params)

  return Taro.switchTab({
    url,
    success: options.success,
    fail: options.fail,
    complete: options.complete,
  })
}

/**
 * 关闭所有页面，打开到应用内的某个页面
 */
export function reLaunch(options: RouterOptions): Promise<any> {
  const url = buildUrl(options.url, options.params)

  return Taro.reLaunch({
    url,
    success: options.success,
    fail: options.fail,
    complete: options.complete,
  })
}

/**
 * 关闭当前页面，返回上一页面或多级页面
 */
export function navigateBack(delta = 1): Promise<any> {
  return Taro.navigateBack({
    delta,
  })
}

/**
 * 导航到首页
 */
export function navigateToHome(params?: Record<string, string | number | boolean>): Promise<any> {
  return navigateTo({
    url: ROUTES.HOME,
    params,
  })
}

/**
 * 导航到登录页
 */
export function navigateToLogin(params?: Record<string, string | number | boolean>): Promise<any> {
  return navigateTo({
    url: ROUTES.LOGIN,
    params,
  })
}

/**
 * 导航到用户中心
 */
export function navigateToUserCenter(params?: Record<string, string | number | boolean>): Promise<any> {
  return navigateTo({
    url: ROUTES.USER_CENTER,
    params,
  })
}
